<?php

namespace app\service;

use app\common\BaseService;
use app\model\Goods as GoodsModel;
use think\facade\Db;

class GoodsService extends BaseService {
  public static function getInstance(): GoodsService {
    return parent::getInstance();
  }

  public static function getModel(): GoodsModel {
    return GoodsModel::getInstance();
  }

  /*
   * 获取商品表列表
   */
  public static function getGoodsList($condition, $page, $pageSize = 10, $orderField='id', $orderSort='DESC') {
    return self::getModel()->list($condition, $page, $pageSize, $orderField, $orderSort);
  }

  /*
   * 根据condition获取商品
   */
  public static function getGoodsByCondition($conditions = [], $order = ['id' => 'asc']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }

  /*
   * 根据ID获取商品表
   */
  public static function getGoodsById($id) {
    return self::getModel()
      ->where('id', '=', $id)
      ->find()
      ->toArray();
  }

  /*
   * 新增商品
   */
  public static function createGoods($data) {
    $data['status'] = 1;
    $data['insert_time'] = date('Y-m-d H:i:s');
    $data['last_update_time'] = date('Y-m-d H:i:s');

    $house = [
      'goods_id' => '',
      'price' => 0,
      'count' => 0,
      'total_amount' => 0,
      'process' => $data['process'],
      'status' => 1,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    self::getModel()->startTrans();
    try {
      // 新增goods表
      $res1 = self::getModel()
        ->insertGetId($data);
      if ($res1 === false) {
        throw new \Exception('新增goods失败');
      }
      if ($res1) {
        // 新增house表
        $house['goods_id'] = $res1;
        $res2 = HouseService::getModel()
          ->save($house);
        if ($res2 === false) {
          throw new \Exception('新增house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 获取商品表列表分页
   */
  public static function getGoodsPager($condition, $page, $pageSize = 10) {
    return self::getModel()->pager($condition, $page, $pageSize);
  }

  /*
   * 更新商品
   */
  public static function updateGoods($id, $fields) {
    // 是否有门店修改分类
    $changeStore = [];
    $goods = self::getModel()->where('id', '=', $id)->find()->toArray();
    if ($goods['category_id'] !== $fields['category_id']) {
      // 获取分类名
      $catName = CategoryService::getModel()->where('id', '=', $fields['category_id'])->find()->toArray()['category_name'];
      // 门店下是否有该商品
      $storeGoods = StoreService::getInstance()->getStoreByCondition([['goods_id', $id, '='],['status', 1, '=']]);
      if ($storeGoods) {
        // 获取该分类的base分类ID
        $categoryList = CategoryService::getInstance()->getCategoryByCondition([['category_name', $catName, '=']]);
        $categoryList = array_column($categoryList, 'id', 'base');
        foreach ($storeGoods as $store) {
          $changeStore[] = [
            'id' => $store['id'],
            'category_id' => isset($categoryList[$store['base']]) ? $categoryList[$store['base']] : '',
            'last_update_time' => date('Y-m-d H:i:s')
          ];
        }
      }
    }
    self::getModel()->startTrans();
    try {
      // 更新goods
      $result = self::getModel()
        ->where('id','=', $id)
        ->save($fields);
      if($result === false) {
        throw new \Exception('更新goods失败');
      }

      // 更新store
      if ($changeStore) {
        $result2 = StoreService::getModel()->saveAll($changeStore);
        if($result2 === false) {
          throw new \Exception('更新store失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 获取商品分类
   */
  public function categoryAll() {
    return Db::table('category')
      ->select()
      ->toArray();
  }

  /*
   * 获取总部商品与库存
   */
  public function getGoodsHouse($conditions, $order = ['g.id' => 'DESC']) {
    $query = self::getModel()
      ->alias('g')
      ->field('g.*, h.count, c.category_name')
      ->join('house h', 'h.goods_id = g.id', 'LEFT')
      ->join('category c', 'g.category_id = c.id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    $result = $query->select()->toArray();
    return $result;
  }

  /*
   * 通过condition获取商品
   */
  public function getDataByCondition($conditions) {
    return self::getModel()->getDataByCondition($conditions);
  }

  /**
   * 获取门店商品
   */
  public function getStoreGoods($base, $conditions = [], $order = ['g.id'=>'desc']) {
    $res = Db::table('goods')
      ->alias('g')
      ->field('g.*, c.category_name')
      ->join('store_house sh', "sh.goods_id = g.id AND sh.base = $base", 'LEFT')
      ->join('category c', 'c.id = g.category_id', 'LEFT');
    if ($conditions) {
      foreach ($conditions as $item) {
        list($field, $value, $op) = $item;
        if (!$op) {
          $op = '=';
        }
        $res->where($field, $op, $value);
      }
    }
    return $res->order($order)
      ->select()
      ->toArray();
  }
}